<template>
  <div class="save-load">
    <div class="save-load-header">
      <h3>💾 分子数据管理</h3>
      <p>保存当前分子数据到本地或从本地文件加载</p>
    </div>

    <div class="save-load-content">
      <!-- 保存功能 -->
      <div class="save-section">
        <h4>保存当前分子</h4>
        <div class="save-options">
          <div class="option-group">
            <label>文件名:</label>
            <input
              v-model="saveFileName"
              placeholder="输入保存文件名"
              :disabled="!materialData"
            />
          </div>
          
          <div class="option-group">
            <label>包含数据:</label>
            <div class="checkbox-group">
              <label>
                <input type="checkbox" v-model="includeStructure" />
                晶体结构数据
              </label>
              <label>
                <input type="checkbox" v-model="includeResearch" />
                研究论文数据
              </label>
              <label>
                <input type="checkbox" v-model="includePrices" />
                市场价格数据
              </label>
            </div>
          </div>

          <button 
            @click="saveData" 
            :disabled="!canSave"
            class="save-btn"
          >
            💾 保存到本地
          </button>
        </div>
      </div>

      <!-- 分隔线 -->
      <div class="divider"></div>

      <!-- 加载功能 -->
      <div class="load-section">
        <h4>从本地加载</h4>
        <div class="load-options">
          <div class="file-input-group">
            <label class="file-input-label">
              📁 选择分子数据文件
              <input
                type="file"
                ref="fileInput"
                accept=".json,.txt"
                @change="handleFileSelect"
                style="display: none"
              />
            </label>
            <span class="file-name" v-if="selectedFile">
              已选择: {{ selectedFile.name }}
            </span>
          </div>

          <div v-if="loadedData" class="preview-section">
            <h5>文件预览:</h5>
            <div class="preview-content">
              <p><strong>材料:</strong> {{ loadedData.materialData?.formula_pretty || '未知' }}</p>
              <p><strong>ID:</strong> {{ loadedData.materialData?.material_id || '未知' }}</p>
              <p><strong>包含数据:</strong> 
                {{ loadedData.structureData ? '结构 ' : '' }}
                {{ loadedData.papers ? '论文 ' : '' }}
                {{ loadedData.prices ? '价格' : '' }}
              </p>
            </div>
            
            <button @click="loadData" class="load-btn">
              📤 加载数据
            </button>
          </div>

          <div v-else class="no-file-selected">
            <p>请选择之前保存的分子数据文件 (.json 格式)</p>
          </div>
        </div>
      </div>

      <!-- 最近保存的文件 -->
      <div class="recent-files" v-if="recentFiles.length > 0">
        <h4>最近保存的文件</h4>
        <div class="recent-files-list">
          <div 
            v-for="(file, index) in recentFiles" 
            :key="index"
            class="recent-file-item"
            @click="loadRecentFile(file)"
          >
            <span class="file-icon">📄</span>
            <div class="file-info">
              <div class="file-name">{{ file.name }}</div>
              <div class="file-date">{{ formatDate(file.timestamp) }}</div>
            </div>
            <span class="file-formula">{{ file.materialData?.formula_pretty }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 状态提示 -->
    <div v-if="statusMessage" :class="['status-message', statusType]">
      {{ statusMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const props = defineProps({
  materialData: {
    type: Object,
    default: null
  },
  structureData: {
    type: Object,
    default: null
  },
  papers: {
    type: Array,
    default: () => []
  },
  prices: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['loadData'])

const saveFileName = ref('')
const includeStructure = ref(true)
const includeResearch = ref(true)
const includePrices = ref(true)
const selectedFile = ref(null)
const loadedData = ref(null)
const recentFiles = ref([])
const statusMessage = ref('')
const statusType = ref('info')
const fileInput = ref(null)

const canSave = computed(() => {
  return props.materialData && saveFileName.value.trim()
})

const formatDate = (timestamp) => {
  return new Date(timestamp).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const showStatus = (message, type = 'info') => {
  statusMessage.value = message
  statusType.value = type
  setTimeout(() => {
    statusMessage.value = ''
  }, 3000)
}

const saveData = () => {
  if (!canSave.value) return

  const dataToSave = {
    materialData: props.materialData,
    timestamp: new Date().toISOString(),
    version: '1.0'
  }

  if (includeStructure.value && props.structureData) {
    dataToSave.structureData = props.structureData
  }

  if (includeResearch.value && props.papers.length > 0) {
    dataToSave.papers = props.papers
  }

  if (includePrices.value && props.prices.length > 0) {
    dataToSave.prices = props.prices
  }

  try {
    const jsonData = JSON.stringify(dataToSave, null, 2)
    const blob = new Blob([jsonData], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `${saveFileName.value}.json`
    link.click()
    
    URL.revokeObjectURL(url)
    
    // 添加到最近文件列表
    const recentFile = {
      name: `${saveFileName.value}.json`,
      timestamp: new Date().toISOString(),
      materialData: props.materialData
    }
    
    recentFiles.value.unshift(recentFile)
    // 保持最近文件列表不超过5个
    if (recentFiles.value.length > 5) {
      recentFiles.value = recentFiles.value.slice(0, 5)
    }
    
    // 保存到localStorage
    localStorage.setItem('recentMolecularFiles', JSON.stringify(recentFiles.value))
    
    showStatus('数据保存成功！', 'success')
    saveFileName.value = ''
    
  } catch (error) {
    console.error('保存失败:', error)
    showStatus('保存失败，请重试', 'error')
  }
}

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (!file) return

  selectedFile.value = file
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const fileContent = e.target.result
      loadedData.value = JSON.parse(fileContent)
      
      // 验证文件格式
      if (!loadedData.value.materialData) {
        throw new Error('无效的分子数据文件格式')
      }
      
      showStatus('文件加载成功，可以导入数据', 'success')
    } catch (error) {
      console.error('文件解析错误:', error)
      showStatus('文件格式错误，请选择有效的JSON文件', 'error')
      loadedData.value = null
    }
  }
  
  reader.onerror = () => {
    showStatus('文件读取失败', 'error')
    loadedData.value = null
  }
  
  reader.readAsText(file)
}

const loadData = () => {
  if (!loadedData.value) return
  
  emit('loadData', loadedData.value)
  showStatus('数据加载成功！', 'success')
  
  // 清空选择
  if (fileInput.value) {
    fileInput.value.value = ''
  }
  selectedFile.value = null
  loadedData.value = null
}

const loadRecentFile = (fileInfo) => {
  // 这里应该从存储中加载实际文件内容
  // 由于安全限制，我们只能提示用户重新选择文件
  showStatus('请使用"选择文件"按钮加载该文件', 'info')
}

// 从localStorage加载最近文件列表
onMounted(() => {
  const savedRecentFiles = localStorage.getItem('recentMolecularFiles')
  if (savedRecentFiles) {
    try {
      recentFiles.value = JSON.parse(savedRecentFiles)
    } catch (error) {
      console.error('加载最近文件列表失败:', error)
    }
  }
})
</script>

<style scoped>
.save-load {
  height: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
}

.save-load-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.save-load-header h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.save-load-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.save-load-content {
  max-width: 600px;
  margin: 0 auto;
}

.save-section,
.load-section {
  margin-bottom: 30px;
}

.save-section h4,
.load-section h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
}

.option-group {
  margin-bottom: 15px;
}

.option-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #495057;
}

.option-group input[type="text"] {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
}

.option-group input[type="text"]:focus {
  border-color: #007bff;
  outline: none;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
  cursor: pointer;
}

.checkbox-group input[type="checkbox"] {
  width: 16px;
  height: 16px;
}

.save-btn,
.load-btn {
  width: 100%;
  padding: 12px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}

.save-btn:hover:not(:disabled),
.load-btn:hover:not(:disabled) {
  background: #218838;
}

.save-btn:disabled,
.load-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.divider {
  height: 1px;
  background: #e9ecef;
  margin: 25px 0;
}

.file-input-group {
  margin-bottom: 15px;
}

.file-input-label {
  display: inline-block;
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.file-input-label:hover {
  background: #0056b3;
}

.file-name {
  display: block;
  margin-top: 8px;
  font-size: 12px;
  color: #6c757d;
}

.preview-section {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
}

.preview-section h5 {
  margin: 0 0 10px 0;
  color: #495057;
}

.preview-content p {
  margin: 5px 0;
  font-size: 14px;
}

.no-file-selected {
  text-align: center;
  padding: 20px;
  color: #6c757d;
  font-style: italic;
}

.recent-files {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

.recent-files h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.recent-files-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.recent-file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
}

.recent-file-item:hover {
  background: #e9ecef;
}

.file-icon {
  font-size: 20px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.file-date {
  font-size: 12px;
  color: #6c757d;
}

.file-formula {
  background: #007bff;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-message {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  z-index: 1000;
}

.status-message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-message.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}
</style>